package com.example.d4_homework.homework04;

import java.util.Random;

public class Test {
    public static void main(String[] args) {
        // 需求：某公司的技术部门年会需要举行一个抽奖活动以感谢员工在这一年中的付出奖品种类总共有4种：一等奖、二等级、三等奖、谢谢惠顾为了节约成本需要控制每一种奖项的抽取概率
        // 常见的做法就是给每一个奖项分配一个int类型的权重值,权重越大抽取到的概率就越大
        // 定义奖项数组,并为其设置值
        Awards[] awards = new Awards[4];
        awards[0] = new Awards("一等奖", 1);
        awards[1] = new Awards("二等奖", 2);
        awards[2] = new Awards("三等奖", 3);
        awards[3] = new Awards("谢谢惠顾", 4);

        // 初始化权重区间
        int cumulativeWeight = 0;
        for (int i = 0; i < awards.length; i++) {
            if (i == 0) {
                awards[i].setLow(cumulativeWeight);
                cumulativeWeight += awards[i].getWeight();
                awards[i].setHigt(cumulativeWeight - 1);
            } else {
                awards[i].setLow(cumulativeWeight);
                cumulativeWeight += awards[i].getWeight();
                awards[i].setHigt(cumulativeWeight - 1);
            }
        }

        // 生成一个0到累积权重-1之间的随机数代表权重
        Random r = new Random();
        int randomWeight = r.nextInt(cumulativeWeight); // 确保随机数在权重区间范围内

        // 查找中奖结果
        Awards award = binarySearch(awards, randomWeight);
        System.out.println("随机权重数: " + randomWeight);
        if (award != null) {
            System.out.println("中奖结果: " + award.getName());
        } else {
            System.out.println("未找到匹配的奖项");
        }
    }

    /**
     * 二分法查找
     *
     * @param awards 奖品数组
     * @param num    奖品权重值
     * @return 奖品对象
     */
    public static Awards binarySearch(Awards[] awards, int num) {
        int left = 0;
        int right = awards.length - 1;
        while (left <= right) {
            int mid = (left + right) >>> 1; // 使用无符号右移避免溢出
            Awards midAward = awards[mid];
            if (num < midAward.getLow()) {
                right = mid - 1;
            } else if (num > midAward.getHigt()) {
                left = mid + 1;
            } else {
                return midAward;
            }
        }
        return null;
    }
}